<?php

namespace app\api\controller;

use app\admin\model\Imessage;
use app\admin\model\Order;
use app\admin\model\PayQrcode;
use app\admin\model\Subscribe;
use app\common\controller\Api;
use app\common\model\CashLog;
use think\Db;

/**
 * 首页接口
 */
class Index extends Api
{

    protected $noNeedLogin = ['index','policy','get_chip','notice_list','notice_detail','news_list','news_detail'];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     * 
     */
    public function index()
    {
        halt($this->auth->getToken());
        $this->success('请求成功');
    }

    /*
     * 用户隐私协议
     * */
    public function policy()
    {
        $imessage = new Imessage();
        $where['status']  =  config('ArticleStatus.Show');
        $where['type']  =   config('ArticleType.Policy');
        $field = 'id,title,content,time,view,user_id';

        $service = $imessage
            ->field($field)
            ->where($where)
            ->order('time desc')
            ->find();

        if (!$service)
        {
            $service = '暂时不需要签署协议';
        }

        $this->success('用户协议',$service);
    }

    /*
     * 认筹活动
     * */
    public function get_chip(){
        $sub = new Subscribe();
        $time = time();
        $where = [
            'begin_time' => ['<',$time],
            'end_time' => ['>',$time],
        ];
        $sub_detail = $sub
            ->where($where)
            ->order('begin_time desc')
            ->find();

        if (!$sub_detail) $this->error('认筹已结束或还没开始');

        //  虚拟购买量
        if ($sub_detail->residue > $sub_detail->virtual_num)
        {
            $sub_detail->residue = $sub_detail->residue - $sub_detail->virtual_num;
        }
        $this->success('认筹活动',$sub_detail);
    }

    /*
     * 组团认筹
     * */
    public function  recognition_chip(){
        $validate_result= $this->validate($this->request->request(),'Index.chip');
        if ($validate_result !== true) $this->error($validate_result);

        $chip_id = $this->request->request('chip_id');
        $chip_num = $this->request->request('chip_num');
        $pay_password = $this->request->request('pay_password');

        $user = $this->auth->getUser(); //  用户信息
        if (empty($user->pay_password)) $this->error('请先设置支付密码');
        if ($this->auth->getEncryptPassword($pay_password,$user->salt) !== $user->pay_password) $this->error('支付密码错误');
        /*if ($user->enable != 1) $this->error('用户还未激活，请先完成实名认证');
        if ($user->is_realname != 1) $this->error('用户还未实名，无法交易');*/

        //  查询认筹交易
        $chip_act = Subscribe::get($chip_id);
        if (!$chip_act)$this->error('活动不存在');
        if ($chip_num  + $chip_act->virtual_num > $chip_act->residue)
        {
            $this->error('剩余量不足，无法认筹',['residue' => $chip_act->residue]);
        }
        //  最大认购额度
        // $total_coin = db('order')->where('subscribe_id','=',$chip_id)->sum('coin');
        // if ($chip_act->max < $total_coin) $this->error('不能超过用户最大认购额度：'.$chip_act->max);
        //  判断用户余额
        $total_price = $chip_num * $chip_act->price;   //  认筹订单总价
        if ($total_price > $user->cash_money) $this->error('用户余额不足，请先充值',['cash' => $user->cash_money]);

        //  获取交易类型
        $cash_type = config('CashType.ExchangeOut');
        $order_type = config('OrderType.CoinIn');
        //  交易后用户表的信息更改（认筹云币冻结）
        $user_data = [
            'cash_money'    =>  $user->cash_money - $total_price,
            'cloud_money_release'   =>  $user->cloud_money_release + $chip_num
        ];

        //  完成交易，生成订单
        $extend = [
            'status'    =>  config('PayStatus.Finished'),
            'subscribe_id'  =>  $chip_id
        ];
        $order_id = create_order($user->id,0,$total_price,$chip_num,$order_type,$cash_type,'组团认筹',$extend,$user_data);

        //  认筹量扣除
        $chip_act->residue = $chip_act->residue - $chip_num;
        $chip_act->save();


        //  判断是否需要推广奖励
        $chip_start = config('site.chip_gift_start');
        if (($chip_start == 0 ) || $chip_num > $chip_start)
        {
            //  认筹推广奖励
            $rc_send = config('site.open_generalize_gift') / 100;   //  认筹推广奖励
            $money_percent = (config('site.open_generalize_gift_money')  /  100) * $rc_send;
            $coin_percent = (config('site.open_generalize_gift_coin')  /  100) * $rc_send;

            //
            $money_send = $total_price * $money_percent;    //  总返回的金额
            $coin_send = $chip_num * $coin_percent; //  总返回的币

            $uids = db('user_invite_log')->where('user_id','=',$user->id)->find();

            if ($uids)
            {
                for ($i=1;$i<=4;$i++)
                {

                    $usid = $uids['invite_'.$i];
                    $money_award = config('site.invite_award_'.$i) / 100 * $money_send;
                    $coin_award = config('site.invite_award_'.$i) / 100 * $coin_send;

                    $tus = new \app\common\model\User();
                    $us = $tus->where('id','=',$usid)->find();
                    if ($us && $us->id > 0)
                    {
                        Db::startTrans();
                        try{
                            //  记录
                            $time = time();
                            $or = new Order;
                            $or->data([
                                'order_id'  =>  generate_order_id($usid),   //  生成随机订单
                                'owner_id'  =>  0,
                                'user_id'   =>  $usid,
                                'cash'      =>  0,
                                'coin'      =>  $coin_award,
                                'detail'    =>  '推广赠送'.$coin_award.'云币',
                                'type'      =>  config('OrderType.Other'),
                                'status'    =>  config('PayStatus.Finished'),
                                'pay_manner'=>  0,
                                'time'      =>  $time
                            ]);
                            $or->save();
                            //
                            $cash_log = new CashLog;
                            $cash_log->data([
                                'user_id'   =>  $usid,
                                'value'     =>  $money_award,
                                'detail'    =>  '推广赠送'.$money_award.'元',
                                'type'      =>  config('CashType.ExchangeIn'),
                                'pay_manner'=>  0,
                                'time'      =>  $time,
                                'status'    =>  config('PayStatus.Finished'),
                                'order_id'  =>  $or->order_id
                            ]);
                            $cash_log->save();
                            //  用户数据
                            $us->data([
                                'cash_money'    =>  $us->cash_money + $money_award,
                                'cloud_money'   =>  $us->cloud_money + $coin_award
                            ]);
                            $us->save();
                            // 提交事务
                            Db::commit();
                        } catch (\Exception $e) {
                            // 回滚事务
                            Db::rollback();
                        }

                    }
                }
            }
        }

        //
        $data = [
            'order_id'  =>  $order_id,
            //'pay_url'   =>  request()->domain().'/uploads/20180702/e4b9f93c9e60dc31f1c43a7615734dd1.jpg'
        ];
        $this->success('认筹成功',$data);
    }



    /*
     * 公告中心列表
     * */
    public function notice_list()
    {
        $imessge = new Imessage();
        $where['status']    =   config('ArticleStatus.Show');
        $where['type']    =   config('ArticleType.Notice');

        //  过滤列表字段
        $field = 'id article_id,title,time';

        $notice_list = $imessge
            ->field($field)
            ->where($where)
            ->order('time desc')
            ->select();

        $this->success('公告中心列表',$notice_list);
    }
    /*
     * 公告中心详情
     * */
    public function notice_detail()
    {
        $validate_result = $this->validate($this->request->request(),'Index.notice');
        if ($validate_result !== true) $this->error($validate_result);

        $aid = $this->request->request('article_id');
        $imessage = new Imessage();
        $where['id'] = $aid;
        $where['status']  = config('ArticleStatus.Show');
        $where['type']  = config('ArticleType.Notice');

        $field = 'id,title,content,user_id,time,view';

        //  查询文章
        $detail = $imessage
            ->field($field)
            ->where($where)
            ->find();

        if ($detail)
        {
            $notice_detail = $detail->getData();
            $notice_detail['auther'] = $detail->user->nickname;
            $notice_detail['time_text'] = $detail->time_text;

            $this->success('公告中心详情',$notice_detail);
        }else
        {
            $this->error('公告不存在或已被删除');
        }

    }

    /*
     * 资讯列表
     * */
    public function news_list()
    {
        $imessge = new Imessage();
        $where['status']    =   config('ArticleStatus.Show');
        $where['type']    =   config('ArticleType.Message');

        //  过滤列表字段
        $field = 'id article_id,title,time';

        $notice_list = $imessge
            ->field($field)
            ->where($where)
            ->order('time desc')
            ->select();

        $this->success('资讯列表',$notice_list);
    }
    /*
     * 资讯详情
     * */
    public function news_detail()
    {
        $validate_result = $this->validate($this->request->request(),'Index.notice');
        if ($validate_result !== true) $this->error($validate_result);

        $aid = $this->request->request('article_id');
        $imessage = new Imessage();
        $where['id'] = $aid;
        $where['status']  = config('ArticleStatus.Show');
        $where['type']  = config('ArticleType.Message');

        $field = 'id,title,content,user_id,time,view';

        //  查询文章
        $detail = $imessage
            ->field($field)
            ->where($where)
            ->find();

        if ($detail)
        {
            $notice_detail = $detail->getData();
            $notice_detail['auther'] = $detail->user->nickname;
            $notice_detail['time_text'] = $detail->time_text;

            $this->success('资讯详情',$notice_detail);
        }else
        {
            $this->error('资讯不存在或已被删除');
        }
    }

    /*
     * 获取充值二维码
     * */
    public function get_pay_code()
    {
        $validate_result = $this->validate($this->request->request(),'Index.pay');
        if ($validate_result !== true) $this->error($validate_result);

        $user = $this->auth->getUser();
        $paynum = $this->request->request('pay_num');
        $paytype = $this->request->request('pay_type');

        if (!array_key_exists($paytype,config('PayTypeArr'))) $this->error('支付方式错误');

        //  查询是否低于最低充值金额
        if ($paynum < config('site.min_recharge')) $this->error('不能低于最低充值金额 '.config('site.min_recharge').' 元');

        //  查询未完成订单
        $twhere = [
            'user_id'=>$user->id,
            'status'=>[['<',config('PayStatus.Finished')],['>',config('PayStatus.Invalid')]],
            ];
        $undone = config('site.undone_order');
        if (db('order')->where($twhere)->count() > $undone)$this->error('您当前未完成订单超过 '.$undone.' 单，请先等待订单完成');



        //  如果是银行卡充值
        if ($paytype == '3'){
            //  创建订单
            $detail = '充值'.$paynum.'元';
            $extend = [
                'status' => config('PayStatus.Unpaid'),
                'data' => json_encode(['pay_type'=>$paytype,'pay_code_id'=>0]),
                'pay_manner'    =>  $paytype
            ];
            $order_id = create_order($user->id,0,$paynum,0,config('OrderType.Other'),config('CashType.Recharge'),$detail,$extend);
            $bank_result = [
                'bank_card_num'  =>  config('site.main_bank_card_num'),
                'bank_card_name'    =>  config('site.main_bank_card_name'),
                'bank_card_address'    =>  config('site.main_bank_card_address'),
                'order_id'      =>  $order_id,
                'tip'       =>    '转账时请备注此订单号'
            ];
            $this->success('银行卡支付信息',$bank_result);
        }


        //  如果是二维码充值
        $qrcode = new PayQrcode();
        $url = $qrcode
            ->where(['pay_type'=>$paytype,'status'=>1])
            ->order('uploadtime','desc')
            ->find();

        if (!$url)
        {
            $this->error('充值二维码不存在，请联系管理员');
        }

        //  创建订单
        $detail = '充值'.$paynum.'元';
        $extend = [
            'status' => config('PayStatus.Unpaid'),
            'data' => json_encode(['pay_type'=>$paytype,'pay_code_id'=>$url->id]),
            'pay_manner'    =>  $paytype
        ];

        $order_id = create_order($user->id,0,$paynum,0,config('OrderType.Other'),config('CashType.Recharge'),$detail,$extend);


        $url->url = $this->request->domain() . $url->url;
        $data = ['order_id' => $order_id,'url' => $url->url,'tip' => '转账时请备注此订单号'];

        $this->success('充值二维码',$data);
    }

    /*
     * 提现
     * */
    public function withdraw()
    {
        $validate_result = $this->validate($this->request->request(),'Index.withdraw');
        if ($validate_result !== true) $this->error($validate_result);


        $wd_num = $this->request->request('wd_num');    //  提现金额
        $pay_manner = $this->request->request('pay_manner');    //  提现方式

        if ($wd_num < config('site.withdraw'))
        {
            $this->error('不能低于最低提现金额'.config('site.withdraw').'元');
        }
        if (!in_array($pay_manner,array_flip(config('PayTypeArr'))))
        {
            $this->error('提现方式不正确，换个姿势再试一下');
        }

        //
        $user = $this->auth->getUser();

        if ($user->enable != 1)
        {
            $this->error('请先实名认证');
        }

        if ($wd_num > $user->cash_money)
        {
            $this->error('提现金额大于用户总金额');
        }

        $user->cash_money = $user->cash_money - $wd_num;
        $user->cash_money_freeze = $user->cash_money_freeze + $wd_num;
        $data = [
            'user_id'   =>  $user->id,
            'value'     =>  $wd_num,
            'detail'    =>  '提现'.$wd_num.'元',
            'type'      =>  config('CashType.Withdraw'),
            'pay_manner'=>  $pay_manner,
            'time'      =>  time(),
            'status'    =>  1
        ];


        $cash_log = new CashLog();

        $result = $cash_log->save($data) && $user->save();

        if ($result == true)
        {
            $this->success('提交成功，请耐心等待审核',['cash_money'=>$user->cash_money]);
        }else
        {
            $this->error('提交失败，请联系管理员');
        }
    }

    /*public function test()
    {

        $list = Db::name('order')
            ->where('time','<',1531112455)
            ->where('type','=',2)
            ->select();

        $e_u = '';
        foreach ($list as $item)
        {
            $chip_num = $item['coin'];
            $user_id = $item['user_id'];


            $chip_start = config('site.chip_gift_start');
            if (($chip_start == 0 ) || $chip_num > $chip_start)
            {
                //  认筹推广奖励
                $rc_send = config('site.open_generalize_gift') / 100;   //  认筹推广奖励
                $money_percent = config('site.open_generalize_gift_money')  /  100;
                $coin_percent = config('site.open_generalize_gift_coin')  /  100;

                $send_num = $rc_send * $chip_num;   //  总赠送量
                $money_send = $send_num * $money_percent;
                $coin_send = $send_num * $coin_percent;

                $uids = db('user_invite_log')->where('user_id','=',$user_id)->find();

                if ($uids)
                {
                    for ($i=1;$i<=4;$i++)
                    {

                        $usid = $uids['invite_'.$i];
                        $money_award = config('site.invite_award_'.$i) / 100 * $total_price ;    //  赠送所有的购款百分比
                        $coin_award = config('site.invite_award_'.$i) / 100 * $chip_num ;    //  赠送所有的币
                        $tus = new \app\common\model\User();
                        $us = $tus->where('id','=',$usid)->find();
                        if ($us && $us->id > 0)
                        {
                            Db::startTrans();
                            try{
                                //  记录
                                $time = time();
                                $or = new Order;
                                $or->data([
                                    'order_id'  =>  generate_order_id($usid),   //  生成随机订单
                                    'owner_id'  =>  0,
                                    'user_id'   =>  $usid,
                                    'cash'      =>  0,
                                    'coin'      =>  $coin_award,
                                    'detail'    =>  '推广赠送'.$coin_award.'云币',
                                    'type'      =>  config('OrderType.Other'),
                                    'status'    =>  config('PayStatus.Finished'),
                                    'pay_manner'=>  0,
                                    'time'      =>  $time
                                ]);
                                $or->save();
                                //
                                $or2 = new Order();
                                $or2->data([
                                    'order_id'  =>  generate_order_id($usid),   //  生成随机订单
                                    'owner_id'  =>  0,
                                    'user_id'   =>  $usid,
                                    'cash'      =>  0,
                                    'coin'      =>  $coin_send,
                                    'detail'    =>  '平台赠送'.$coin_send.'云币',
                                    'type'      =>  config('OrderType.Other'),
                                    'status'    =>  config('PayStatus.Finished'),
                                    'pay_manner'=>  0,
                                    'time'      =>  $time
                                ]);
                                $or2->save();
                                //
                                $cash_log = new CashLog;
                                $cash_log->data([
                                    'user_id'   =>  $usid,
                                    'value'     =>  $money_award,
                                    'detail'    =>  '推广赠送'.$money_award.'元',
                                    'type'      =>  config('CashType.ExchangeIn'),
                                    'pay_manner'=>  0,
                                    'time'      =>  $time,
                                    'status'    =>  config('PayStatus.Finished'),
                                    'order_id'  =>  $or->order_id
                                ]);
                                $cash_log->save();
                                //
                                $cash_log2 = new CashLog();
                                $cash_log2->data([
                                    'user_id'   =>  $usid,
                                    'value'     =>  $money_send,
                                    'detail'    =>  '平台赠送'.$money_send.'元',
                                    'type'      =>  config('CashType.ExchangeIn'),
                                    'pay_manner'=>  0,
                                    'time'      =>  $time,
                                    'status'    =>  config('PayStatus.Finished'),
                                    'order_id'  =>  $or->order_id
                                ]);
                                $cash_log2->save();

                                //  用户数据
                                $us->data([
                                    'cash_money'    =>  $us->cash_money + $money_award + $money_send,
                                    'cloud_money'   =>  $us->cloud_money + $coin_award + $coin_send
                                ]);
                                $us->save();
                                // 提交事务
                                Db::commit();
                            } catch (\Exception $e) {
                                // 回滚事务
                                Db::rollback();
                            }

                        }
                    }
                }
            }
            $e_u .= $user_id.',';

        }

        echo $e_u;
    }*/
}
